# -*- coding: utf-8 -*-
"""
原始模型 vs 优化模型 对比分析
展示两个模型的差异和优化效果
"""

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

def setup_encoding():
    """设置控制台编码，解决中文乱码问题"""
    import sys
    import os
    if sys.platform.startswith('win'):
        os.system('chcp 65001 > nul')
        sys.stdout.reconfigure(encoding='utf-8')
        sys.stderr.reconfigure(encoding='utf-8')

def compare_models():
    """对比两个模型的预测结果"""
    print("=" * 90)
    print("原始模型 vs 优化模型 对比分析")
    print("=" * 90)
    
    # 加载两个模型的结果
    try:
        original = pd.read_csv('factor_result3.csv')
        optimized = pd.read_csv('factor_result_optimized.csv')
    except FileNotFoundError as e:
        print(f"错误：找不到结果文件 - {e}")
        print("请先运行 periodic_factor_v2.py 和 periodic_factor_optimization.py")
        return
    
    # 添加星期信息
    original['report_date'] = pd.to_datetime(original['report_date'], format='%Y%m%d')
    optimized['report_date'] = pd.to_datetime(optimized['report_date'], format='%Y%m%d')
    
    original['weekday'] = original['report_date'].dt.dayofweek
    optimized['weekday'] = optimized['report_date'].dt.dayofweek
    
    original['day'] = original['report_date'].dt.day
    optimized['day'] = optimized['report_date'].dt.day
    
    # 1. 总体统计对比
    print("\n" + "─" * 90)
    print("1. 总体预测统计对比")
    print("─" * 90)
    
    print(f"\n申购金额:")
    print(f"  原始模型: {original['purchase'].sum():>15.2f}")
    print(f"  优化模型: {optimized['purchase'].sum():>15.2f}")
    print(f"  差异    : {optimized['purchase'].sum() - original['purchase'].sum():>15.2f}")
    print(f"  增长率  : {(optimized['purchase'].sum() / original['purchase'].sum() - 1) * 100:>15.2f}%")
    
    print(f"\n赎回金额:")
    print(f"  原始模型: {original['redeem'].sum():>15.2f}")
    print(f"  优化模型: {optimized['redeem'].sum():>15.2f}")
    print(f"  差异    : {optimized['redeem'].sum() - original['redeem'].sum():>15.2f}")
    print(f"  增长率  : {(optimized['redeem'].sum() / original['redeem'].sum() - 1) * 100:>15.2f}%")
    
    # 2. 按星期几的对比
    print("\n" + "─" * 90)
    print("2. 按星期几的预测对比")
    print("─" * 90)
    
    weekday_names = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    
    print(f"\n{'星期':<6} {'原始申购':>15} {'优化申购':>15} {'差异':>15} {'差异率':>10}")
    print("─" * 65)
    
    for day in range(7):
        orig_data = original[original['weekday'] == day]
        optim_data = optimized[optimized['weekday'] == day]
        
        if not orig_data.empty and not optim_data.empty:
            orig_sum = orig_data['purchase'].sum()
            optim_sum = optim_data['purchase'].sum()
            diff = optim_sum - orig_sum
            diff_rate = (optim_sum / orig_sum - 1) * 100 if orig_sum != 0 else 0
            
            print(f"{weekday_names[day]:<6} {orig_sum:>15.0f} {optim_sum:>15.0f} {diff:>15.0f} {diff_rate:>9.2f}%")
    
    # 3. 按日期的对比（月初、月中、月末）
    print("\n" + "─" * 90)
    print("3. 按日期周期的预测对比")
    print("─" * 90)
    
    periods = {
        '月初(1-10日)': (1, 10),
        '月中(11-20日)': (11, 20),
        '月末(21-30日)': (21, 30)
    }
    
    print(f"\n{'周期':<15} {'原始申购':>15} {'优化申购':>15} {'差异':>15} {'差异率':>10}")
    print("─" * 65)
    
    for period_name, (start_day, end_day) in periods.items():
        orig_data = original[(original['day'] >= start_day) & (original['day'] <= end_day)]
        optim_data = optimized[(optimized['day'] >= start_day) & (optimized['day'] <= end_day)]
        
        if not orig_data.empty and not optim_data.empty:
            orig_sum = orig_data['purchase'].sum()
            optim_sum = optim_data['purchase'].sum()
            diff = optim_sum - orig_sum
            diff_rate = (optim_sum / orig_sum - 1) * 100 if orig_sum != 0 else 0
            
            print(f"{period_name:<15} {orig_sum:>15.0f} {optim_sum:>15.0f} {diff:>15.0f} {diff_rate:>9.2f}%")
    
    # 4. 日均预测对比
    print("\n" + "─" * 90)
    print("4. 日均预测统计")
    print("─" * 90)
    
    print(f"\n申购日均:")
    print(f"  原始模型: {original['purchase'].mean():>15.2f}")
    print(f"  优化模型: {optimized['purchase'].mean():>15.2f}")
    print(f"  差异    : {optimized['purchase'].mean() - original['purchase'].mean():>15.2f}")
    
    print(f"\n赎回日均:")
    print(f"  原始模型: {original['redeem'].mean():>15.2f}")
    print(f"  优化模型: {optimized['redeem'].mean():>15.2f}")
    print(f"  差异    : {optimized['redeem'].mean() - original['redeem'].mean():>15.2f}")
    
    # 5. 波动性分析
    print("\n" + "─" * 90)
    print("5. 预测稳定性对比（标准差越小越稳定）")
    print("─" * 90)
    
    print(f"\n申购标准差:")
    print(f"  原始模型: {original['purchase'].std():>15.2f}")
    print(f"  优化模型: {optimized['purchase'].std():>15.2f}")
    print(f"  改善比例: {(1 - optimized['purchase'].std() / original['purchase'].std()) * 100:>14.2f}%")
    
    print(f"\n赎回标准差:")
    print(f"  原始模型: {original['redeem'].std():>15.2f}")
    print(f"  优化模型: {optimized['redeem'].std():>15.2f}")
    print(f"  改善比例: {(1 - optimized['redeem'].std() / original['redeem'].std()) * 100:>14.2f}%")
    
    # 6. 极值分析
    print("\n" + "─" * 90)
    print("6. 预测极值对比")
    print("─" * 90)
    
    print(f"\n申购预测:")
    print(f"  {'':6} {'最小值':>15} {'最大值':>15} {'最小值':>15} {'最大值':>15}")
    print(f"  {'':6} {'原始模型':>15} {'原始模型':>15} {'优化模型':>15} {'优化模型':>15}")
    print(f"  {'-'*60}")
    print(f"  {'值':6} {original['purchase'].min():>15.0f} {original['purchase'].max():>15.0f} "
          f"{optimized['purchase'].min():>15.0f} {optimized['purchase'].max():>15.0f}")
    
    # 7. 详细日期对比（前10天）
    print("\n" + "─" * 90)
    print("7. 详细日期对比（前10天）")
    print("─" * 90)
    
    print(f"\n{'日期':<12} {'星期':<6} {'原始申购':>15} {'优化申购':>15} {'差异':>15} {'差异率':>10}")
    print("─" * 80)
    
    for i in range(min(10, len(original))):
        orig_row = original.iloc[i]
        optim_row = optimized.iloc[i]
        
        date_str = orig_row['report_date'].strftime('%Y-%m-%d')
        weekday = weekday_names[int(orig_row['weekday'])]
        orig_purchase = orig_row['purchase']
        optim_purchase = optim_row['purchase']
        diff = optim_purchase - orig_purchase
        diff_rate = (optim_purchase / orig_purchase - 1) * 100 if orig_purchase != 0 else 0
        
        print(f"{date_str:<12} {weekday:<6} {orig_purchase:>15.0f} {optim_purchase:>15.0f} "
              f"{diff:>15.0f} {diff_rate:>9.2f}%")
    
    # 8. 优化效果总结
    print("\n" + "─" * 90)
    print("8. 优化效果总结")
    print("─" * 90)
    
    # 计算相关指标
    purchase_improvement = (optimized['purchase'].std() / original['purchase'].std() - 1) * 100
    redeem_improvement = (optimized['redeem'].std() / original['redeem'].std() - 1) * 100
    
    correlation_orig = original['purchase'].corr(original['redeem'])
    correlation_optim = optimized['purchase'].corr(optimized['redeem'])
    
    print(f"\n稳定性改善:")
    print(f"  申购预测波动率变化: {purchase_improvement:+.2f}% (负数表示波动减小，更稳定)")
    print(f"  赎回预测波动率变化: {redeem_improvement:+.2f}%")
    
    print(f"\n申购赎回相关性:")
    print(f"  原始模型: {correlation_orig:.4f}")
    print(f"  优化模型: {correlation_optim:.4f}")
    
    print(f"\n预测值分布特征:")
    print(f"  {'':20} {'申购(原)':>15} {'申购(优)':>15} {'赎回(原)':>15} {'赎回(优)':>15}")
    print(f"  {'平均值':20} {original['purchase'].mean():>15.0f} {optimized['purchase'].mean():>15.0f} "
          f"{original['redeem'].mean():>15.0f} {optimized['redeem'].mean():>15.0f}")
    print(f"  {'中位数':20} {original['purchase'].median():>15.0f} {optimized['purchase'].median():>15.0f} "
          f"{original['redeem'].median():>15.0f} {optimized['redeem'].median():>15.0f}")
    print(f"  {'四分位数(25%)':20} {original['purchase'].quantile(0.25):>15.0f} "
          f"{optimized['purchase'].quantile(0.25):>15.0f} {original['redeem'].quantile(0.25):>15.0f} "
          f"{optimized['redeem'].quantile(0.25):>15.0f}")
    print(f"  {'四分位数(75%)':20} {original['purchase'].quantile(0.75):>15.0f} "
          f"{optimized['purchase'].quantile(0.75):>15.0f} {original['redeem'].quantile(0.75):>15.0f} "
          f"{optimized['redeem'].quantile(0.75):>15.0f}")
    
    # 9. 保存对比结果
    print("\n" + "─" * 90)
    print("9. 保存对比结果")
    print("─" * 90)
    
    comparison_df = pd.DataFrame({
        'report_date': original['report_date'].astype(str),
        'weekday': original['weekday'],
        'day': original['day'],
        'original_purchase': original['purchase'],
        'optimized_purchase': optimized['purchase'],
        'purchase_diff': optimized['purchase'] - original['purchase'],
        'purchase_diff_rate': ((optimized['purchase'] - original['purchase']) / original['purchase'] * 100).round(2),
        'original_redeem': original['redeem'],
        'optimized_redeem': optimized['redeem'],
        'redeem_diff': optimized['redeem'] - original['redeem'],
        'redeem_diff_rate': ((optimized['redeem'] - original['redeem']) / original['redeem'] * 100).round(2)
    })
    
    comparison_df.to_csv('model_comparison_results.csv', index=False, encoding='utf-8')
    print("\n对比结果已保存到 model_comparison_results.csv")
    
    # 10. 建议
    print("\n" + "─" * 90)
    print("10. 优化建议")
    print("─" * 90)
    
    print("""
✓ 优化模型的优势:
  1. 考虑月内周期特征（上旬、中旬、下旬）
  2. 加入样本置信度权重
  3. 支持多种交互项组合策略
  4. 预测更稳定，波动更小
  5. 更符合真实业务逻辑

💡 何时使用优化模型：
  • 数据样本不均衡的情况
  • 需要捕捉月内周期性变化
  • 对预测精度要求高
  • 希望减少预测波动

⚠ 注意事项：
  • 优化模型计算量略多，但在可接受范围内
  • 参数可根据业务情况调整
  • 建议定期更新因子，以适应数据变化
    """)
    
    print("=" * 90)
    print("对比分析完成！")
    print("=" * 90)

def main():
    """主函数"""
    setup_encoding()
    compare_models()

if __name__ == "__main__":
    main()
